package com.eiokey.linkbus.livedata;

import android.widget.Button;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

/**
 * description  即能更新view，又能建立livedata模式的监听
 * use
 * param
 * return
 * @author JetQiao
 * @date 2021/7/23  16:37
 */

public class ObservableLiveData<T> extends ObservableField<T> {
    MutableLiveData<T> nMutableLiveData;
    private static final int START_VERSION = -1;
    private int mVersion = START_VERSION;

    /**
     * Creates an empty observable object
     */
    public ObservableLiveData() {
        super();
    }

    /**
     * Wraps the given object and creates an observable object
     * @param value The value to be wrapped as an observable.
     */
    public ObservableLiveData(T value) {
        super(value);
        mVersion++;
    }

    @Override
    public void set(T value) {
        super.set(value);
        mVersion++;
        if (nMutableLiveData != null) {
            nMutableLiveData.postValue(value);
        }
    }


    public T getValue() {
        return get();
    }

    private void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer, boolean stick) {
        activeMutableLiveData(stick);
        nMutableLiveData.observe(owner, observer);
    }

    @MainThread
    private void observeForever(@NonNull Observer<T> observer, boolean stick) {
        activeMutableLiveData(stick);
        nMutableLiveData.observeForever(observer);
    }

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        observe(owner, observer, true);
    }

    @MainThread
    public void observeForever(@NonNull Observer<T> observer) {
        observeForever(observer, true);
    }

    public boolean hasActiveObservers() {
        return nMutableLiveData != null && nMutableLiveData.hasActiveObservers();
    }

    public boolean hasObservers() {
        return nMutableLiveData != null && nMutableLiveData.hasObservers();
    }

    private void activeMutableLiveData(boolean stick) {
        if (nMutableLiveData == null) {
            // 没有绑定时不发送，绑定了之后发送
            nMutableLiveData = new MutableLiveData<T>();
            if (mVersion > START_VERSION) {
                nMutableLiveData.setValue(get());
            }
        } else {

        }
    }
}
